// edit-baoming.js
const http = require('../../utils/http.js');

Page({
  data: {
      base_candidate_info:{
        recognitionResult: '',
        recording: false,  // 用于标记当前是否正在录音
      isPaused: false,   // 用于标记录音是否处于暂停状态
      recordFilePath: '',  // 用于保存录音文件的临时路径
      editableContent: '', // 用于保存识别后文本内容的初始化
      buttonText: '开始录音', // 新增按钮文本控制变量
      },
    baoming_candidate_info: {
      id_number: '',
      vocational_college_id: null,
      vocational_major_id: null,
      candidate_type_id: null,
      exam_center_city_id: null,
      exam_major_id: null,
      volunteer_college_id: null,
      volunteer_major_id: null,
      is_certificate_issued: '否'
    },
    vocationalColleges: [],
    vocationalCollegeMajors: [],
    candidateTypes: [],
    examCenters: [],
    examMajors: [],
    volunteerColleges: [],
    volunteerCollegeMajors: [],

    vocationalCollegeIndex: null,
    vocationalCollegeMajorIndex: null,
    candidateTypeIndex: null,
    examCenterIndex: null,
    examMajorIndex: null,
    volunteerCollegeIndex: null,
    volunteerCollegeMajorIndex: null,

    count : 0
  },

  onLoad() {
    this.loadOptions().then(() => {
      this.loadStoredInfo();
    }).catch(err => {
      console.error('加载数据失败:', err);
    });
  },

  async loadOptions() {
    try {
      const promises = [
        this.fetchOptions('/vocationalcollege/list', 'vocationalColleges'),
        this.fetchOptions('/candidateType/list', 'candidateTypes'),
        this.fetchOptions3('/city/list', 'examCenters'),
        this.fetchOptions('/major/list', 'examMajors'),
        this.fetchOptions('/volunteercollege/list', 'volunteerColleges')
      ];
  
      await Promise.all(promises);
      console.log('所有数据加载完成');
      this.loadStoredInfo();
    } catch (err) {
      console.error('加载选项失败:', err);
    }
  },
  
  async loadStoredInfo() {
    const storedInfo = wx.getStorageSync('baoming_candidate_info');
    if (storedInfo) {
      this.setData({
        baoming_candidate_info: storedInfo
      });
      // 确保志愿和专科专业数据正确加载后再设置下标
      await this.loadvvMajors();
      this.updateIndexes(storedInfo);
    }
  }
  ,
  
  async loadvvMajors() {
    const fields = ['volunteerCollege', 'vocationalCollege'];
    for (const element of fields) {
      const college_id = `${element}_id`;
      const id = this.data.baoming_candidate_info[college_id];
      if (id) {
        const endpoint = element === 'vocationalCollege' ? `/vocationalmajor/listByCollegeId?collegeId=${id}` : `/volunteermajor/listByCollegeId?collegeId=${id}`;
        await this.fetchOptions(endpoint, `${element}Majors`);
      }
    }
  },
  
  updateIndexes(storedInfo) {
    const indexes = {
      vocationalCollegeIndex: this.findIndexById(this.data.vocationalColleges, storedInfo.vocational_college_id),
      vocationalCollegeMajorIndex: this.findIndexById(this.data.vocationalCollegeMajors, storedInfo.vocational_major_id),
      candidateTypeIndex: this.findIndexById(this.data.candidateTypes, storedInfo.candidate_type_id),
      examCenterIndex: this.findIndexById(this.data.examCenters, storedInfo.exam_center_city_id),
      examMajorIndex: this.findIndexById(this.data.examMajors, storedInfo.exam_major_id),
      volunteerCollegeIndex: this.findIndexById(this.data.volunteerColleges, storedInfo.volunteer_college_id),
      volunteerCollegeMajorIndex: this.findIndexById(this.data.volunteerCollegeMajors, storedInfo.volunteer_major_id)
    };
  
    // 更新下标
    for (const key in indexes) {
      if (indexes[key] !== -1) {
        console.log(`${key}: ${indexes[key]}`);
        this.setData({ [key]: indexes[key] });
      } else {
        console.warn(`未找到 ${key} 的索引，可能是数据未加载或 id 不匹配`);
      }
    }
  },
  
  findIndexById(options, id) {
    if (!options || !Array.isArray(options)) {
      console.error('选项数据无效或不是数组:', options);
      return -1;
    }
    const index = options.findIndex(option => option.id == id);
    if (index === -1) {
      console.warn(`未找到匹配的 id (${id})，在选项:`, options);
    }
    return index;
  },
  

  fetchOptions(endpoint, stateKey, mapField = 'name') {
    return new Promise((resolve, reject) => {
      http.get(endpoint).then(res => {
        if (res.data.code === 200) {
          const data = res.data.data && Array.isArray(res.data.data) ? res.data.data : (res.data.rows || []);
          const formattedData = data.map(item => ({
            id: item.id,
            name: item[mapField]
          }));
          this.setData({ [stateKey]: formattedData }, resolve);
        } else {
          reject('数据加载失败');
        }
      }).catch(err => {
        reject(err);
      });
    });
  },

  fetchOptions3(endpoint, stateKey) {
    return new Promise((resolve, reject) => {
      http.get(endpoint).then(res => {
        if (res.statusCode === 200) {
          const formattedData = res.data.map(item => ({
            id: item.id,
            name: item.cityName
          }));
          this.setData({ [stateKey]: formattedData }, resolve);
        } else {
          reject('数据加载失败');
        }
      }).catch(err => {
        reject(err);
      });
    });
  },

//   handlePickerChange(e) {
//     const { field } = e.currentTarget.dataset;
//     const index = e.detail.value;
//     const id = this.data[`${field}s`][index].id;

//     this.setData({
//       [`baoming_candidate_info.${field}_id`]: id,
//       [`${field}Index`]: index
//     });

//     if (field === 'volunteerCollege' || field === 'vocationalCollege') {
//       const endpoint = field === 'vocationalCollege' ? `/vocationalmajor/listByCollegeId?collegeId=${id}` : `/volunteermajor/listByCollegeId?collegeId=${id}`;
//       this.fetchOptions(endpoint, `${field}Majors`);
//     }
//   },

handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    const id = this.data[`${field}s`][index]?.id;
  
    if (!id) {
      console.error(`选项数据中未找到有效的 id，field: ${field}, index: ${index}`);
      return;
    }
  
    this.setData({
      [`baoming_candidate_info.${field}_id`]: id,
      [`${field}Index`]: index
    });
  
    // 加载志愿或专科专业选项
    if (field === 'volunteerCollege' || field === 'vocationalCollege') {
      const endpoint = field === 'vocationalCollege' 
        ? `/vocationalmajor/listByCollegeId?collegeId=${id}` 
        : `/volunteermajor/listByCollegeId?collegeId=${id}`;
      this.fetchOptions(endpoint, `${field}Majors`).then(() => {
        console.log(`${field}Majors 数据加载成功`);
      }).catch(err => {
        console.error(`加载 ${field}Majors 数据失败:`, err);
      });
    }
  },  

  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`baoming_candidate_info.${field}`]: e.detail.value
    });
  },

  handleSubmit() {
    http.post('/candidate/updateRegistrationInfo', this.data.baoming_candidate_info).then(res => {
      if (res.statusCode === 200) {
        wx.setStorageSync('baoming_candidate_info', this.data.baoming_candidate_info);
        wx.showToast({ title: '报考信息更新成功', duration: 2000 });
        wx.navigateTo({ url: '/pages/edit-post/edit-post' });
      }
    }).catch(err => {
      console.error('报考信息更新失败:', err);
      wx.showToast({ title: '报考信息更新失败', icon: 'none' });
    });
  },

  handleNavigateBack() {
    wx.navigateTo({ url: '/pages/edit-base/edit-base' });
  },

  checkRecordPermission() {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.record']) {
                    console.log('已获取录音权限，直接resolve');
                    resolve();
                } else {
                    wx.authorize({
                        scope: 'scope.record',
                        success() {
                            console.log('申请录音权限成功，resolve');
                            resolve();
                        },
                        fail() {
                            console.log('申请录音权限失败，reject');
                            reject('用户未授予录音权限');
                        }
                    });
                }
            },
            fail() {
                console.log('获取录音权限设置失败，reject');
                reject('获取录音权限设置失败');
            }
        });
    });
},
  


toggleRecording() {
    const that = this;
    if (that.data.recording) {
        // 停止录音逻辑
        that.setData({ recording: false });
        const recorderManager = wx.getRecorderManager();
        recorderManager.stop();
        recorderManager.onStop((res) => {
            // 将录音文件临时路径存储到本地存储
            wx.setStorageSync('recordPath', res.tempFilePath);
            that.setData({ recordFilePath: res.tempFilePath });
            // 这里调用后端代码进行录音转文字
            // that.setData({ editableContent: '转换后的文本内容' });
            that.setData({ buttonText: '开始录音' });
        });
    } else {
        that.checkRecordPermission().then(() => {
            // 开始录音逻辑
            that.setData({ recording: true });
            const recorderManager = wx.getRecorderManager();
            recorderManager.start({
                format: 'wav', // 设置为wav格式
                duration: 60000, 
                sampleRate: 44100, 
                numberOfChannels: 1, 
                encodeBitRate: 96000
            });
            that.setData({ buttonText: '停止录音' });
        }).catch((error) => {
            wx.showToast({
                title: 'error',
                icon:'none'
            });
        });
    }
},

// 上传录音并进行语音识别函数
uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
        wx.showToast({ title: '请先录制录音', icon: 'none' });
        return;
    }
    wx.uploadFile({
        filePath: this.data.recordFilePath,
        name: 'audio_data',
        url: baseUrl + '/recognize',
        formData: {},
        header: { 'content-type': 'multipart/form-data' },
        success: function (res) {
            try {
                const responseData = JSON.parse(res.data);
                if (responseData.code === 200 && responseData.text) {
                    this.setData({
                        editableContent: responseData.text
                    });
                    // 调用函数将识别结果发送到另一个端口
                    this.sendRecognitionResultToServer(responseData.text).then(() => {
                        // 这里可以添加成功发送后的其他逻辑，比如提示用户等
                        wx.showToast({
                            title: '识别结果已成功发送到其他端口',
                            icon: 'success',
                            duration: 2000
                        });
                    }).catch(err => {
                        console.log('发送识别结果到其他端口失败:', err);
                        wx.showToast({
                            title: '识别结果发送到其他端口失败，请稍后重试',
                            icon: 'none',
                            duration: 2000
                        });
                    });
                } else {
                    wx.showToast({
                        title: responseData.message || '识别出现其他错误',
                        icon: 'none',
                        duration: 2000
                    });
                }
            } catch (e) {
                console.log('无法解析识别结果：', e);
                console.log('接收到的原始返回数据：', res.data);
            }
        }.bind(this),
        fail: function (err) {
            console.log('上传失败，详细错误信息：', err);
            if (err.errMsg.includes('network')) {
                wx.showToast({
                    title: '网络连接出现问题，请检查网络设置后重试',
                    icon: 'none',
                    duration: 2000
                });
            } else if (err.errMsg.includes('file')) {
                wx.showToast({
                    title: '文件相关错误，请检查音频文件是否正常',
                    icon: 'none',
                    duration: 2000
                });
            } else {
                wx.showToast({
                    title: '上传出现其他未知错误，请稍后重试',
                    icon: 'none',
                    duration: 2000
                });
            }
        }
    });
},
// 发送识别结果到另一个端口的函数，确保以JSON格式发送
sendRecognitionResultToServer(result) {
    const resultToSend = {
        text: result
    };
    return new Promise((resolve, reject) => {
        const options = {
            url: 'http://localhost:8088/files/files/fillData',
            method: 'POST',
            header: {
                'content-type': 'application/json' // 设置请求头为JSON格式
            },
            data: {}
        };
        try {
            options.data = JSON.stringify(resultToSend); // 对要发送的数据进行JSON序列化
        } catch (jsonError) {
            console.log('JSON序列化识别结果失败:', jsonError);
            reject('识别结果数据格式错误');
            return;
        }
        http.request(options).then(res => {
            if (res.data && res.data.code === 200) {
                console.log('识别结果已成功发送到服务器');
                resolve();
            } else {
                console.log('发送识别结果到服务器失败', res);
                reject('发送识别结果到服务器失败');
            }
        }).catch(err => {
            console.log('发送识别结果到服务器请求失败', err);
            reject(err);
        });
    });
}
});